//
//  UIViewControllerExtensions.swift
//  MYGrow
//
//  Created by 小火科技 on 2024/3/4.
//

import UIKit

extension UIViewController {
    static var currentViewController: UIViewController? {
        getCurrentViewController()
    }
    
    static var keyWindow: UIWindow? {
        UIApplication.shared.connectedScenes.filter{$0.activationState == .foregroundActive}.map{$0 as? UIWindowScene}.compactMap{$0}.first?.windows.filter{$0.isKeyWindow}.first
    }
    
    private static func getCurrentViewController(_ base: UIViewController? = nil) -> UIViewController? {
        var root = base
        if root == nil {
            root = keyWindow?.rootViewController
        }
        
        if let nav = root as? MYGNavigationController {
            return getCurrentViewController(nav.visibleViewController)
        }
        
        if let present = root?.presentedViewController {
            return getCurrentViewController(present)
        }
        
        if let tab = root as? MYGTabBarController {
            if let selected = tab.selectedViewController {
                return getCurrentViewController(selected)
            }
        }
        
        return root
    }
}
